import type { CascaderProps } from 'ant-design-vue';

import { reactive, ref, watch } from 'vue';

import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';

import {
  addOrUpdateAddressApi,
  getAddressListApi,
  getAreaListApi,
} from '#/api';
import { useTable } from '#/hooks/useTable';
import { link1688stor } from '#/store';

export const addressStore = defineStore('address', () => {
  const link1688 = link1688stor();
  const infosearchForm = {
    pageNum: 1,
    pageSize: 20,
    sellerLoginId: '',
  };
  let searchForm = reactive({
    ...infosearchForm,
  });

  const {
    tableData,
    page,
    loading,
    resetParams,
    getList,
    handleCurrentChange,
    handleSizeChange,
  } = useTable({
    apiFn: getAddressListApi,
    params: searchForm,
    immediate: false,
    // isPageable: false,
  });
  const formStateInfo: any = {
    receiveName: '',
    receivePhone: '',
    addressDetail: '',
    province: '',
    provinceCode: '',
    city: '',
    cityCode: '',
    area: '',
    areaCode: '',
    town: '',
    townCode: '',
    remark: '',
    sellerLoginId: '',
  };
  const formStateA: any = ref({ ...formStateInfo });
  const activeKey = ref('1');
  const showAddBoxState = ref(false);
  const selectSetItemInfoData: any = ref(null);
  const seletInListAddersId = ref(null);
  const add4AreaList = ref([]);
  const getInterOuter = ref([]);

  function $reset() {
    showAddBoxState.value = false;
    selectSetItemInfoData.value = null;
    searchForm = reactive({ ...infosearchForm });
    seletInListAddersId.value = null;
    add4AreaList.value = [];
    getInterOuter.value = [];
    activeKey.value = '1';
    formStateA.value = { ...formStateInfo };
  }
  watch(showAddBoxState, () => {
    if (!showAddBoxState.value) {
      $reset();
    }
  });

  function openSeletctAddress(record: any) {
    // infosearchForm.sellerLoginId = record.wangwangAccount;
    //
    showAddBoxState.value = true;
    selectSetItemInfoData.value = record;
    if (record.aliSaleAddress) {
      seletInListAddersId.value = record.aliSaleAddress.tbId;
    }
    searchForm.sellerLoginId = record.wangwangAccount;
    getList();
    getAreaListApiFn(1);
  }

  async function addOrUpdateAddressApiFn() {
    activeKey.value === '1' ? editAddess() : addAddress();
  }
  async function editAddess() {
    const nowSelectItem = tableData.value.find(
      (item: any) => item.tbId === seletInListAddersId.value,
    );
    nowSelectItem.sellerLoginId =
      selectSetItemInfoData?.value?.wangwangAccount ||
      nowSelectItem.sellerLoginId;

    loading.value = true;
    await addOrUpdateAddressApi(nowSelectItem).finally(() => {
      // $reset();
      loading.value = false;
    });
    showAddBoxState.value = false;
    loading.value = false;
    link1688.getList();
  }
  function addAddress() {
    chengtsfehr(getInterOuter.value);

    // link1688.getList();
  }

  async function chengtsfehr(e: any) {
    const formStateB = { ...formStateA.value };
    formStateB.province = '';
    formStateB.provinceCode = '';
    formStateB.city = '';
    formStateB.cityCode = '';
    formStateB.area = '';
    formStateB.areaCode = '';
    formStateB.town = '';
    formStateB.townCode = '';
    add4AreaList.value.forEach((item: any) => {
      if (item.code === e[0]) {
        formStateB.province = item.name;
        formStateB.provinceCode = item.code;
        item.children.forEach((item1: any) => {
          if (item1.code === e[1]) {
            formStateB.city = item1.name;
            formStateB.cityCode = item1.code;
            item1.children.forEach((item2: any) => {
              if (item2.code === e[2]) {
                formStateB.area = item2.name;
                formStateB.areaCode = item2.code;
                item2.children.forEach((item3: any) => {
                  if (item3.code === e[3]) {
                    formStateB.town = item3.name;
                    formStateB.townCode = item3.code;
                  }
                });
              }
            });
          }
        });
      }
    });
    formStateB.sellerLoginId =
      selectSetItemInfoData?.value?.wangwangAccount || '';

    formStateB.addressDetail = `${formStateB.province}${formStateB.city}${formStateB.area}${formStateB.town}${formStateB.addressDetail}`;
    loading.value = true;
    await addOrUpdateAddressApi(formStateB).finally(() => {
      // $reset();
      loading.value = false;
    });
    // showAddBoxState.value = false;
    loading.value = false;
    formStateA.value = { ...formStateInfo };
    // for (const key in formStateA.value) {
    //   formStateA.value[key] = formStateInfo[key];
    // }
    getInterOuter.value = [];
    message.success('添加成功');
    getList();
    link1688.getList();
  }
  async function getAreaListApiFn(code: any) {
    // console.log('getData', getData);
    add4AreaList.value = await getArressList(code);
  }
  async function getArressList(code: any) {
    const getData = await getAreaListApi({ fatherCode: code });
    return getData.map((item: any) => {
      item.isLeaf = item.level === 'Town';
      return item;
    });
  }

  const loadData: CascaderProps['loadData'] = async (selectedOptions) => {
    const targetOption: any = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    const datase = await getArressList(targetOption.code);
    targetOption.loading = false;
    targetOption.children = datase;
  };

  return {
    $reset,
    showAddBoxState,
    openSeletctAddress,
    tableData,
    page,
    loading,
    resetParams,
    getList,
    handleCurrentChange,
    handleSizeChange,
    activeKey,
    seletInListAddersId,
    addOrUpdateAddressApiFn,
    getAreaListApiFn,
    add4AreaList,
    loadData,
    getInterOuter,
    formStateA,
    selectSetItemInfoData,
  };
});
